<template>
  <div class="userChatRobot">

    <van-nav-bar :title="robotName" left-text="返回" left-arrow @click-left="onClickLeft" @click-right="onClickRight">
      <template #right>
        <van-icon name="ellipsis" class="chatSetting"/>
      </template>
    </van-nav-bar>
    <van-pull-refresh :disabled="disAble" v-model="isLoading" success-text="刷新成功" @refresh="onRefresh">
      <div class="imageSpace"
           :style="{ background: `url(${imgUrl}) center fixed` }"
      >
        <div class="chat" v-for="item in chatList" :key="item.uuid">
          <div :class="item.contentClass" @click="chatContent">
            <van-image class="robotImage" src="https://img01.yzcdn.cn/vant/cat.jpeg"/>
            <div class="chatMessage">
              <span class="item.type">{{ item.prompt }}</span>
              <div class="image" v-if="item.imageUrl" @click="preViewImage(item.imageUrl)">
                <van-image :src="item.imageUrl">
                  <template v-slot:loading>
                    <van-loading type="spinner" size="20"/>
                  </template>
                  <template v-slot:error>加载...</template>
                </van-image>
                <span :id="item.taskId">{{ item.description }}</span>
              </div>
              <!-- <div class="operate" v-show="item.type == 'ai' && item.operateShow && item.imageUrl"> -->
              <div class="operate" v-show="item.type == 'ai'">
                <van-button type="primary">放大</van-button>
                <van-button type="default" @click="chooseImage('U1',item.taskId)">U1</van-button>
                <van-button type="default" @click="chooseImage('U2',item.taskId)">U2</van-button>
                <van-button type="default" @click="chooseImage('U3',item.taskId)">U3</van-button>
                <van-button type="default" @click="chooseImage('U4',item.taskId)">U4</van-button>
                <van-button class="replay" type="default" @click="replayImage">
                  <van-icon name="replay"/>
                </van-button>
              </div>
              <div class="operate" v-show="'item.type' == 'ai'">
                <van-button type="primary">变换</van-button>
                <van-button type="default" @click="chooseImage('V1')">V1</van-button>
                <van-button type="default" @click="chooseImage('V2')">V2</van-button>
                <van-button type="default" @click="chooseImage('V3')">V3</van-button>
                <van-button type="default" @click="chooseImage('V4')">V4</van-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-pull-refresh>


    <van-tabbar>
      <div class="chatInput">
        <van-dropdown-menu direction="up">
          <van-dropdown-item v-model="imageRobotType" :options="imageRobotTypeList"/>
          <van-dropdown-item v-model="imageType" :options="imageTypeList"/>
          <van-dropdown-item v-model="belike" :options="belikeList"/>
        </van-dropdown-menu>
        <van-field v-model="prompt" rows="2" type="textarea" maxlength="300" placeholder="请输入..." show-word-limit
                   clearable>
          <template #button>
            <van-button size="small" type="primary" @click="sendMessage" :disable="isDraw">发送</van-button>
          </template>
        </van-field>
      </div>
    </van-tabbar>
  </div>
</template>


<script>
// :style="{ backgroundImage: `url(${imgUrl}) center no-repeat` }" 
import {v4 as uuidv4} from 'uuid'
import {createImage, findTask, simpleChange} from '@/api/user/userImage';
import {findByRobotId} from '@/api/user/robotInfo'
import {ImagePreview} from 'vant';
// --ar 16:19 图片的比例  --stylize 艺术感 --niji  --iw 图像权重 默认是0.25 
// --stylize/-s 0-1000：数值越大图片和文字关联性越大 （测试效果不明显）
// https://docs.qq.com/doc/DR1V1S2JYUWd5Q29l
// --chaos：更改结果的变异程度（0–100）。较高的值会产生更不寻常和意外的结果
export default {
  name: 'ImageInfo',
  props: {
    robotId: {
      required: true,
      type: String,
      default: '123'
    },
    robotName: {
      required: true,
      type: String,
      default: '小何'
    }
  },
  data() {
    return {
      prompt: '一个传白衣服的18岁的小女孩',
      isShow: false,
      operateShow: false,
      imageRobotType: 'MIDJOURNEY',
      imageType: '',
      belike: '-s 500',
      taskId: '',
      base64Array: '',
      isDraw: false,
      lastAiImage: {},
      count: 0,
      isLoading: false,
      currentPage: 1,
      disAble: false,
      belikeList: [
        {text: '默认', value: '-s 500'},
        {text: '高相似度', value: '-s 1000'},
        {text: '低相似度', value: '-s  0'}
      ],
      imageTypeList: [
        {text: '写实', value: ''},
        {text: '动漫', value: '--niji'}
      ],
      imageRobotTypeList: [
        {text: 'dalle3', value: 'DALLE'},
        {text: 'midjourney', value: 'MIDJOURNEY'}
      ],
      chatList: [
        {
          uuid: 'id1',
          prompt: '我是真正的聊天内容呀',
          type: 'user',
          taskId: '1704631227808059',
          imageUrl: 'https://cdn.discordapp.com/attachments/1183277222358950011/1193424937814343881/mrhe_dis_one_18_year_old_girl_b95f5b3a-6060-413d-963b-8dce13a81006.png?ex=65acaa95&is=659a3595&hm=71ce3401fbc4cbeb50b12fc0179a37e340876300949718c240ceb808b3fe62d6&',
          contentClass: 'chatContent user'
        },
        {
          uuid: 'id2',
          prompt: '我是真正的聊天内容呀',
          type: 'ai',
          taskId: '1704631227808060',
          imageUrl: 'https://cdn.discordapp.com/attachments/1183277222358950011/1193556258918236230/mrhe_dis_An_18-year-old_girl_wearing_white_clothes_holding_an_o_d9e0b64a-0b0b-4e48-94ea-a13b0bdcecbd.png?ex=65ad24e3&is=659aafe3&hm=ae5b61cde7e104e3d738d87c04748d37131aa9767e18d6f308f41448b1f87be1&',
          contentClass: 'chatContent ai'
        }
      ],
      imgUrl: 'https://img01.yzcdn.cn/vant/cat.jpeg'
    }
  },
  components: {},
  computed: {},
  methods: {
    preViewImage(imageUrl) {
      ImagePreview([
        imageUrl
      ])
    },
    onClickLeft() {
      this.$toast('返回');
      this.$router.push({
        name: 'chatHome'
      })
    },
    onClickRight() {
      this.$toast('更多信息啊');
      this.$router.push({
        name: 'robotSetting'
      })
    },
    chatContent() {
      this.operateShow = true
      const interval = setInterval(() => {
        this.operateShow = false;
      }, 2500);
    },
    async chooseImage(desc, taskId) {
      const param = {
        content: taskId+" "+ desc,
        robotId: this.robotId
      }
      const { data } = await simpleChange(param)
      this.doDealDraw(data)
      console.log('chooseImage', desc, taskId)
    },
    async sendMessage() {
      let count = 0
      const uuid = uuidv4()
      // 用户数据
      const userChat = {
        uuid: uuid,
        taskId: uuid,
        prompt: this.prompt,
        type: 'user',
        contentClass: 'chatContent user'
      }

      this.chatList.push(userChat)
      this.isDraw = true
      // console.log('sendMessage',this.prompt)
      let state = ''
      if (this.imageType) {
        state = state + this.imageType + ' '
      }
      if (this.belike) {
        state = state + this.belike + ' '
      }
      // return
      // 发送请求 开始画图
      const createImageData = {
        prompt: this.prompt,
        uuid: uuid,
        base64Array: [],
        state: state,
        robotId: this.robotId
      }
      const mockData = {
        data: {
          code: 200,
          prompt: 'ceshi ',
          uuid: 'id12',
          type: 'ai',
          taskId: '17046312278080601',
          imageUrl: 'https://cdn.discordapp.com/attachments/1183277222358950011/1193424937814343881/mrhe_dis_one_18_year_old_girl_b95f5b3a-6060-413d-963b-8dce13a81006.png?ex=65acaa95&is=659a3595&hm=71ce3401fbc4cbeb50b12fc0179a37e340876300949718c240ceb808b3fe62d6&',
          contentClass: 'chatContent ai'
        }
      }
      // const { data } = await createImage(createImageData)
      const data = mockData
      console.log('绘画任务返回值: ', data)
      this.doDealDraw(data)
    },
    doDealDraw(data){
      if (data.data.code === 200) {
        const realAi = data.data
        this.taskId = realAi.taskId
        realAi.type = 'ai'
        realAi.contentClass = 'chatContent ai'
        realAi.operateShow = true
        realAi.prompt = realAi.message
        this.lastAiImage = realAi
        this.chatList.push(realAi)
        console.log('创建绘画返回值: ', realAi, this.lastAiImage)
        // 开始同步任务查询
        const timer = setInterval(async () => {
          count++
          const {data: taskData} = await findTask("1705592761535749")
          const realTaskTimeData = taskData.data
          console.info('setTimeout taskData', realTaskTimeData, this.lastAiImage, count)
          if (!realTaskTimeData && count < 10) {
            console.warn("Task not found", taskData, realTaskTimeData)
            return
          } else {
            if (realTaskTimeData.status === 'SUCCESS' || count >= 10) {
              clearInterval(timer)
              this.lastAiImage.imageUrl = realTaskTimeData.imageUrl
              console.info('成功或者失败', this.lastAiImage, realAi)

            } else {
              this.lastAiImage.prompt = realTaskTimeData.progress
              this.lastAiImage.imageUrl = realTaskTimeData.imageUrl
            }
          }
        }, 2500);

        // 开始查询 任务进度
      }

      this.isDraw = false
      // 22 队列中... 什么时候刷新?  等新进来的时候再刷新吧
      if (data.data.code === 22) {
        this.taskId = data.taskId
        const realAi = data.data
        realAi.type = 'ai'
        realAi.contentClass = 'chatContent ai'
        this.lastAiImage = realAi
        this.chatList.push(realAi)
        return
      }
      this.isDraw = false
    },
    onRefresh() {
      console.log("onRefresh")
      setTimeout(() => {
        this.$toast('刷新成功');
        this.isLoading = false;
        this.count++;
      }, 500);
    },
    replayImage() {
      console.log('replayImage')
    },
    loadRobotInfo() {
      console.log('loadRobotInfo')
    }
  },
  created() {
    this.loadRobotInfo()
  }
}
</script>

<style scoped lang='scss'>
.replay {
  justify-self: flex-end;
}

.van-dropdown-menu {
  display: flex;
  justify-content: flex-start;
  margin-right: 5px;
  height: 30px;

}

::v-deep .van-dropdown-menu__item {
  width: 60px;
  height: 28px;
  background-color: rgba(0, 238, 255, 0.037);
  border: 1px solid rgba(0, 0, 0, 0.037);
  margin-right: 15px;
}

.van-tabbar {
  height: 140px;
  max-height: 400px;

}

.chat {
  position: relative;
  top: 47px;

}

.imageSpace {
  height: 600px;
  overflow-y: scroll;
  margin-bottom: 135px;
}

.chatInput {
  width: 100%;
}

.van-nav-bar {
  position: fixed;
  top: 0;
  width: 100%;
}

.van-nav-bar .van-icon {
  font-size: 25px;
  font-weight: 10px;
  color: black;
}

.robotImage {
  width: 48px;
  height: 48px;
  border-radius: 2px;
  overflow: hidden;
  margin: 5px 5px 5px 5px;
}

.chatContent {
  display: flex;

  .chatMessage {
    word-wrap: break-word;
    max-width: 230px;
    font-size: 20px;
    font-weight: 200;
    padding: 10px;
    border-radius: 10px;
    background-color: aliceblue;
    margin: 5px 5px;

    .operate {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      margin-top: 5px;

      .van-button {
        width: 40px;
        height: 20px;
        font-size: 12px;
        text-align: left;
        margin-left: 1px;
      }

    }
  }

}

.van-button--normal {
  padding: 0 0px;
  font-size: 14px;
}

.ai {
  text-align: left;
}

.user {
  text-align: right;
}

.chatContent.user {
  flex-direction: row-reverse;
}

.userChatRobot {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

::v-deep .van-dropdown-menu__bar {

  height: 30px;
}

.van-dropdown-menu__item {
  height: 30px;

  margin-right: 15px;
}

.image {
  width: 230px;
  height: 230px;
  display: flex;
  justify-content: center;
}
</style>
